package com.wfm.mianshi;

/**
 * @author wfm
 * @create 2024-03-27-21:20
 */
public class P判断字符串是否可以不超过一次变成另一个字符串 {
    public static boolean isOneEditAway(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();

        if (Math.abs(len1 - len2) > 1) {
            return false;
        }

        int count = 0;
        int p1 = 0;
        int p2 = 0;

        while (p1 < len1 && p2 < len2) {
            if (str1.charAt(p1) != str2.charAt(p2)) {
                if (count == 1) {
                    return false;
                }

                if (len1 < len2) {
                    p2++;
                } else if (len1 > len2) {
                    p1++;
                } else {
                    p1++;
                    p2++;
                }

                count++;
            } else {
                p1++;
                p2++;
            }
        }

        if (p1 < len1 || p2 < len2) {
            count++;
        }

        return count <= 1;
    }

    //
    public static boolean oneEditAway(String first, String second) {
        int m = first.length(), n = second.length();
        if (n - m == 1) {
            return oneInsert(first, second);
        } else if (m - n == 1) {
            return oneInsert(second, first);
        } else if (m == n) {
            boolean foundDifference = false;
            for (int i = 0; i < m; i++) {
                if (first.charAt(i) != second.charAt(i)) {
                    if (!foundDifference) {
                        foundDifference = true;
                    } else {
                        return false;
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }

    public static  boolean oneInsert(String shorter, String longer) {
        int length1 = shorter.length(), length2 = longer.length();
        int index1 = 0, index2 = 0;
        while (index1 < length1 && index2 < length2) {
            if (shorter.charAt(index1) == longer.charAt(index2)) {
                index1++;
            }
            index2++;
            if (index2 - index1 > 1) {
                return false;
            }
        }
        return true;
    }


    public static void main(String[] args) {
//        System.out.println(isOneEditAway("abc", "abd"));  // true
        System.out.println(oneEditAway("abcd", "abd"));  // true
        System.out.println(oneEditAway("pale", "ple"));  // true
//        System.out.println(isOneEditAway("abc", "abcd"));  // true
//        System.out.println(isOneEditAway("abc", "ab"));  // true
//        System.out.println(isOneEditAway("abc", "def"));  // false
//        System.out.println(isOneEditAway("abc", "abcde"));  // false
    }
}
